import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { userStore } from '@/stores/user' // 导入userStore
import { getVisitorId } from '@/utils/utils'

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 10 * 1000, // 请求超时时间
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

service.interceptors.request.use(async (config: AxiosRequestConfig) => {
  const store = userStore() // 获取store实例
  const token = store.getToken() // 获取token
  const visitorId = await getVisitorId()
  config.headers = config.headers || {}
  if (token) {
    config.headers['token'] = `${token}` // 将token添加到请求头
  }
  config.headers['DeviceId'] = `${visitorId}` // 将访客ID添加到请求头
  return config
})

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data
    if (data.code === 200) {
      return data
    } else {
      return Promise.reject(data)
    }
  },
  (err) => {
    return Promise.reject(err.response)
  }
)

const request = {
  get<T = any>(url: string, data?: any): Promise<T> {
    return request.request('GET', url, { params: data })
  },
  post<T = any>(url: string, data?: any): Promise<T> {
    return request.request('POST', url, { data })
  },
  put<T = any>(url: string, data?: any): Promise<T> {
    return request.request('PUT', url, { data })
  },
  delete<T = any>(url: string, data?: any): Promise<T> {
    return request.request('DELETE', url, { params: data })
  },
  request<T = any>(method = 'GET', url: string, data?: any): Promise<T> {
    return new Promise((resolve, reject) => {
      service({ method, url, ...data })
        .then((res) => {
          resolve(res as unknown as Promise<T>)
        })
        .catch((e: Error | AxiosError) => {
          reject(e)
        })
    })
  }
}

export default request
